package com.rjj.wlqq.tool.excel.excelOne;

import com.rjj.wlqq.tool.io.FileKit;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ExcelWriteStream {
    private static final String XLS = "xls";

    /**
     * 写到输出流
     */
    public static void writeStream(String filename, Workbook wb, HttpServletResponse response, HttpServletRequest request) {

        try (
                ServletOutputStream os = response.getOutputStream();
                OutputStream outputStream = new BufferedOutputStream(os);
        ) {

            if (!filename.contains(XLS)) {
                filename += ".xls";
            }

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;" + FileKit.encodeFileName(request, filename));
            response.setContentType("application/octet-stream;charset=UTF-8");
            wb.write(outputStream);
            outputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
